﻿using System;
using System.Web;
using Tools.Api.Cache;

namespace Tools.Cache {

    /// <summary>
    ///     Adatper模式
    /// 
    /// </summary>
    public class HttpContextCacheAdapter : ICacheStorage {
        public void Remove(string key) {
            HttpContext.Current.Cache.Remove(key);
        }

        public void Store(string key, object data) {
            HttpContext.Current.Cache.Insert(key, data);
        }

        public T Retrieve<T>(string key) {
            T itemStored = (T)HttpContext.Current.Cache.Get(key);
            if (itemStored == null) {
                itemStored = default(T);
            }
            return itemStored;
        }

        public T Pull<T>(string key, Func<T> method) {
            T val = Retrieve<T>(key);
            if (val == null) {
                val = method();
                Store(key, val);
            }
            return val;
        }
    }
}
